package system

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type SeckillOrderApi struct{}

// CreateSeckillOrder 创建秒杀订单表
// @Tags SeckillOrder
// @Summary 创建秒杀订单表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body system.SeckillOrder true "创建秒杀订单表"
// @Success 200 {object} response.Response{msg=string} "创建成功"
// @Router /seckillOrder/createSeckillOrder [post]
func (seckillOrderApi *SeckillOrderApi) CreateSeckillOrder(c *gin.Context) {
	ctx := c.Request.Context()

	var seckillOrder system.SeckillOrder
	err := c.ShouldBindJSON(&seckillOrder)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = seckillOrderService.CreateSeckillOrder(ctx, &seckillOrder)
	if err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("创建成功", c)
}

// DeleteSeckillOrder 删除秒杀订单表
// @Tags SeckillOrder
// @Summary 删除秒杀订单表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body system.SeckillOrder true "删除秒杀订单表"
// @Success 200 {object} response.Response{msg=string} "删除成功"
// @Router /seckillOrder/deleteSeckillOrder [delete]
func (seckillOrderApi *SeckillOrderApi) DeleteSeckillOrder(c *gin.Context) {
	ctx := c.Request.Context()

	ID := c.Query("ID")
	err := seckillOrderService.DeleteSeckillOrder(ctx, ID)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

// DeleteSeckillOrderByIds 批量删除秒杀订单表
// @Tags SeckillOrder
// @Summary 批量删除秒杀订单表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "批量删除成功"
// @Router /seckillOrder/deleteSeckillOrder [delete]
func (seckillOrderApi *SeckillOrderApi) DeleteSeckillOrderByIds(c *gin.Context) {
	ctx := c.Request.Context()

	IDs := c.QueryArray("IDs[]")
	err := seckillOrderService.DeleteSeckillOrderByIds(ctx, IDs)
	if err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("批量删除成功", c)
}

// UpdateSeckillOrder 更新秒杀订单表
// @Tags SeckillOrder
// @Summary 更新秒杀订单表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body system.SeckillOrder true "更新秒杀订单表"
// @Success 200 {object} response.Response{msg=string} "更新成功"
// @Router /seckillOrder/updateSeckillOrder [put]
func (seckillOrderApi *SeckillOrderApi) UpdateSeckillOrder(c *gin.Context) {
	ctx := c.Request.Context()

	var seckillOrder system.SeckillOrder
	err := c.ShouldBindJSON(&seckillOrder)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = seckillOrderService.UpdateSeckillOrder(ctx, seckillOrder)
	if err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("更新成功", c)
}

// FindSeckillOrder 用id查询秒杀订单表
// @Tags SeckillOrder
// @Summary 用id查询秒杀订单表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param ID query uint true "用id查询秒杀订单表"
// @Success 200 {object} response.Response{data=system.SeckillOrder,msg=string} "查询成功"
// @Router /seckillOrder/findSeckillOrder [get]
func (seckillOrderApi *SeckillOrderApi) FindSeckillOrder(c *gin.Context) {
	ctx := c.Request.Context()

	ID := c.Query("ID")
	reseckillOrder, err := seckillOrderService.GetSeckillOrder(ctx, ID)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败:"+err.Error(), c)
		return
	}
	response.OkWithData(reseckillOrder, c)
}

// GetSeckillOrderList 分页获取秒杀订单表列表
// @Tags SeckillOrder
// @Summary 分页获取秒杀订单表列表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.SeckillOrderSearch true "分页获取秒杀订单表列表"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "获取成功"
// @Router /seckillOrder/getSeckillOrderList [get]
func (seckillOrderApi *SeckillOrderApi) GetSeckillOrderList(c *gin.Context) {
	ctx := c.Request.Context()

	var pageInfo systemReq.SeckillOrderSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := seckillOrderService.GetSeckillOrderInfoList(ctx, pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// GetSeckillOrderPublic 不需要鉴权的秒杀订单表接口
// @Tags SeckillOrder
// @Summary 不需要鉴权的秒杀订单表接口
// @Accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=object,msg=string} "获取成功"
// @Router /seckillOrder/getSeckillOrderPublic [get]
func (seckillOrderApi *SeckillOrderApi) GetSeckillOrderPublic(c *gin.Context) {
	ctx := c.Request.Context()

	seckillOrderService.GetSeckillOrderPublic(ctx)
	response.OkWithDetailed(gin.H{
		"info": "不需要鉴权的秒杀订单表接口信息",
	}, "获取成功", c)
}

// SeckillOrderPay 订单支付
// @Tags SeckillOrder
// @Summary 订单支付
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.SeckillOrderSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /seckillOrder/seckillOrderPay [POST]
func (seckillOrderApi *SeckillOrderApi) SeckillOrderPay(c *gin.Context) {
	var req struct {
		OrderSn string `json:"order_sn" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	payURL, err := seckillOrderService.SeckillOrderPay(req.OrderSn)
	if err != nil {
		response.FailWithMessage("获取支付链接失败: "+err.Error(), c)
		return
	}
	response.OkWithData(gin.H{"pay_url": payURL}, c)
}

// AlipayNotify 支付宝回调接口
// @Tags SeckillOrder
// @Summary 支付宝回调接口
// @Accept application/x-www-form-urlencoded
// @Produce application/json
// @Success 200 {string} string "success"
// @Router /seckillOrder/alipayNotify [POST]
func (seckillOrderApi *SeckillOrderApi) AlipayNotify(c *gin.Context) {
	// 获取支付宝回调参数
	params := c.Request.Form
	global.GVA_LOG.Info("支付宝回调参数", zap.Any("params", params))
	
	// 验证签名
	// TODO: 实现支付宝签名验证逻辑
	
	// 处理支付结果
	tradeStatus := params.Get("trade_status")
	outTradeNo := params.Get("out_trade_no")
	
	if tradeStatus == "TRADE_SUCCESS" {
		// 支付成功，更新订单状态并回滚库存
		err := seckillOrderService.HandlePaymentSuccess(outTradeNo)
		if err != nil {
			global.GVA_LOG.Error("处理支付成功失败", zap.Error(err))
			c.String(200, "fail")
			return
		}
		global.GVA_LOG.Info("订单支付成功", zap.String("order_sn", outTradeNo))
	}
	
	c.String(200, "success")
}

// HandlePaymentSuccessManually 手动处理支付成功（用于测试）
// @Tags SeckillOrder
// @Summary 手动处理支付成功
// @Accept application/json
// @Produce application/json
// @Param data body object true "订单号"
// @Success 200 {object} response.Response{msg=string} "处理成功"
// @Router /seckillOrder/handlePaymentSuccess [POST]
func (seckillOrderApi *SeckillOrderApi) HandlePaymentSuccessManually(c *gin.Context) {
	var req struct {
		OrderSn string `json:"order_sn" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	
	err := seckillOrderService.HandlePaymentSuccess(req.OrderSn)
	if err != nil {
		global.GVA_LOG.Error("手动处理支付成功失败", zap.Error(err))
		response.FailWithMessage("处理失败: "+err.Error(), c)
		return
	}
	
	response.OkWithMessage("处理成功", c)
}

// RollbackUnusedStock 活动结束后回滚未用完的库存
// @Tags SeckillOrder
// @Summary 活动结束后回滚未用完的库存
// @Accept application/json
// @Produce application/json
// @Param data body object true "活动ID"
// @Success 200 {object} response.Response{msg=string} "回滚成功"
// @Router /seckillOrder/rollbackUnusedStock [POST]
func (seckillOrderApi *SeckillOrderApi) RollbackUnusedStock(c *gin.Context) {
	var req struct {
		ActivityId uint `json:"activity_id" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	
	err := seckillOrderService.RollbackUnusedStock(req.ActivityId)
	if err != nil {
		global.GVA_LOG.Error("库存回滚失败", zap.Error(err))
		response.FailWithMessage("回滚失败: "+err.Error(), c)
		return
	}
	
	response.OkWithMessage("库存回滚成功", c)
}
